"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.getServerPortByInstanceId = exports.getActiveServers = exports.requestPorts = exports.stopPortManagerServer = exports.startPortManagerServer = exports.isPortManagerServerRunning = exports.isPortManagerPortAvailable = exports.BASE_URL = void 0;
const axios_1 = __importDefault(require("axios"));
const PortManagerServer_1 = require("../utils/PortManagerServer");
const ports_1 = require("../constants/ports");
const logger_1 = require("./logger");
exports.BASE_URL = `http://localhost:${ports_1.PORT_MANAGER_SERVER_PORT}`;
async function isPortManagerPortAvailable() {
    return PortManagerServer_1.PortManagerServer.portAvailable();
}
exports.isPortManagerPortAvailable = isPortManagerPortAvailable;
async function isPortManagerServerRunning() {
    try {
        const { data } = await axios_1.default.get(`${exports.BASE_URL}${PortManagerServer_1.HEALTH_CHECK_PATH}`);
        return data.status === PortManagerServer_1.SERVICE_HEALTHY;
    }
    catch (e) {
        logger_1.logger.debug(e);
        return false;
    }
}
exports.isPortManagerServerRunning = isPortManagerServerRunning;
async function startPortManagerServer() {
    const isRunning = await isPortManagerServerRunning();
    if (!isRunning) {
        await PortManagerServer_1.PortManagerServer.init();
    }
}
exports.startPortManagerServer = startPortManagerServer;
async function stopPortManagerServer() {
    const isRunning = await isPortManagerServerRunning();
    if (isRunning) {
        await axios_1.default.post(`${exports.BASE_URL}/close`);
    }
}
exports.stopPortManagerServer = stopPortManagerServer;
async function requestPorts(portData) {
    const { data } = await axios_1.default.post(`${exports.BASE_URL}/servers`, {
        portData: portData,
    });
    return data.ports;
}
exports.requestPorts = requestPorts;
async function getActiveServers() {
    const { data } = await axios_1.default.get(`${exports.BASE_URL}/servers`);
    return data.servers;
}
exports.getActiveServers = getActiveServers;
async function getServerPortByInstanceId(serverInstanceId) {
    const { data } = await axios_1.default.get(`${exports.BASE_URL}/servers/${serverInstanceId}`);
    return data.port;
}
exports.getServerPortByInstanceId = getServerPortByInstanceId;
async function deleteServerInstance(serverInstanceId) {
    await axios_1.default.delete(`${exports.BASE_URL}/servers/${serverInstanceId}`);
}
exports.deleteServerInstance = deleteServerInstance;
async function portManagerHasActiveServers() {
    const { data } = await axios_1.default.get(`${exports.BASE_URL}/servers`);
    return data.count > 0;
}
exports.portManagerHasActiveServers = portManagerHasActiveServers;
